<script setup lang="ts">
import { reactive, ref, onBeforeUnmount, onMounted } from "vue";
import { useWatermark } from "@pureadmin/utils";
import {
  saveWatermark,
  findWatermark,
  getWatermarkContext
} from "@/api/vap/setting";

const form = reactive({
  baseContent: "", // 基础字段
  customContent: "", // 自定义内容
  color: "", // 颜色
  size: 16, // 字体大小
  globalAlpha: 50, // 透明度
  show: false // 是否需要显示水印
});

const checkList = ref(["username"]);
onBeforeUnmount(() => {
  // 在离开该页面时清除整页水印
  clear();
});

onMounted(() => {
  findWatermark().then(res => {
    const w = JSON.parse(res);
    checkList.value = w.baseContent.split(",");
    form.customContent = w.customContent;
    form.color = w.color;
    form.size = w.size;
    form.globalAlpha = w.globalAlpha;
    form.show = w.true;
  });
});
const onSubmit = () => {
  let t = "";
  checkList.value.forEach(item => {
    t += item;
    t += ",";
  });
  form.baseContent = t.substring(0, t.length - 1);
  const str = JSON.stringify(form);
  saveWatermark(str);
};
const { setWatermark, clear } = useWatermark();

// 获取水印内容并显示
const showWatermark = () => {
  getWatermarkContext().then(res => {
    setWatermark(res, {
      globalAlpha: form.globalAlpha / 100,
      fillStyle: form.color,
      font: form.size + "px Reggae One"
    });
  });
};
</script>

<template>
  <div>
    <el-card>
      <el-form :model="form" label-width="120px">
        <el-form-item label="基础内容">
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="username">账户</el-checkbox>
            <el-checkbox label="nickname">昵称</el-checkbox>
            <el-checkbox label="timeNow">当前时间</el-checkbox>
            <el-checkbox label="sessionId">会话ID</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="自定义内容">
          <el-input v-model="form.customContent" style="width: 400px" />
        </el-form-item>
        <el-form-item label="字体颜色">
          <el-color-picker v-model="form.color" />
        </el-form-item>
        <el-form-item label="字体大小">
          <el-input-number v-model="form.size" :min="1" :max="50" :step="5" />
        </el-form-item>
        <el-form-item label="透明度">
          <el-input-number
            v-model="form.globalAlpha"
            :min="0"
            :max="100"
            :step="10"
          />
        </el-form-item>
        <el-form-item label="显示开关">
          <el-switch v-model="form.show" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="showWatermark">预览</el-button>
          <el-button @click="clear">关闭预览</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped></style>
